﻿using System;

namespace Mp3Observer.Common.IoC
{
    /// <summary>
    /// </summary>
    /// <example>
    /// <code>
    /// <![CDATA[ 
    ///     IPhoneNumber phoneNumber = IoC.Resolve<IPhoneNumber>();
    /// ]]>
    /// </code>
    /// </example>
    public static class IoCFactory
    {
        private static IDependencyResolver _resolver;

        static IoCFactory()
        {
            Initialize();
        }

        private static void Initialize()
        {
            var configuration = IoCSettingsConfigSection.Settings;

            if (configuration == null || configuration.Components.Resolver.IsNullOrEmpty())
                throw new InvalidOperationException("No IoC resolver configuration found in the configuration file");

            Type configuredResolver = Type.GetType(configuration.Components.Resolver, false, true);

            if (configuredResolver == null)
                throw new InvalidOperationException("The IoC resolver found in the configuration file is either an invalid type or could not be found");

            Initialize((IDependencyResolver)Activator.CreateInstance(configuredResolver));
        }

        public static void Initialize(IDependencyResolver resolver)
        {
            _resolver = resolver;
        }

        public static T Resolve<T>()
        {
            return _resolver.Resolve<T>();
        }

        public static T ResolveByName<T>(string name)
        {
            return _resolver.ResolveByName<T>(name);
        }
    }
}
